import _extends from 'babel-runtime/helpers/extends';
import _defineProperty from 'babel-runtime/helpers/defineProperty';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _createClass from 'babel-runtime/helpers/createClass';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import * as React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import isString from 'lodash/isString';
import isFunction from 'lodash/isFunction';
import omit from 'omit.js';
import { getIeVersion } from '../_util/browser';
function fixControlledValue(value) {
    if (typeof value === 'undefined' || value === null) {
        return '';
    }
    return value;
}

function isChrome() {
    if (typeof window !== 'undefined') {
        var win = window;
        return !!win.chrome; // && !!win.chrome.webstore;
    }
    return false;
}

function isNeedTriggerAfterComposition() {
    return isChrome() || getIeVersion() === 11;
}

function upperCaseString(value) {
    if (isString(value)) {
        return value.toUpperCase();
    }
    return undefined;
}

function lowerCaseString(value) {
    if (isString(value)) {
        return value.toLowerCase();
    }
    return undefined;
}
/**
 * 判断是否全角
 */
function isDbc(s) {
    var dbc = false;
    if (isString(s)) {
        for (var i = 0; i < s.length; i++) {
            var c = s.charCodeAt(i);
            if (c > 65248 || c === 12288) {
                dbc = true;
                break;
            }
        }
    }
    return dbc;
}
/**
 * 全角转半角
 */
function dbcToSbc(str) {
    var result = [];
    if (isString(str)) {
        for (var i = 0; i < str.length; i++) {
            var code = str.charCodeAt(i); // 获取当前字符的unicode编码
            if (code >= 65281 && code <= 65373) {
                // 在这个unicode编码范围中的是所有的英文字母已及各种字符
                result.push(String.fromCharCode(code - 65248)); // 把全角字符的unicode编码转换为对应半角字符的unicode码
            } else if (code === 12288) {
                // 空格
                result.push(' ');
            } else {
                result.push(str.charAt(i));
            }
        }
    }
    return result.join('');
}

var Input = function (_React$Component) {
    _inherits(Input, _React$Component);

    function Input() {
        _classCallCheck(this, Input);


        var _this = _possibleConstructorReturn(this, (Input.__proto__ || Object.getPrototypeOf(Input)).apply(this, arguments));

        _this.state = {
            type: 'text',
            showPassword: false
        };
        _this.isOnComposition = false;

        _this.handleShowPassword = function () {
            _this.setState({
                type: 'text',
                showPassword: true
            });
        };

        _this.handleHidePassword = function () {
            _this.setState({
                type: 'password',
                showPassword: false
            });
        };
        _this.handleKeyDown = function (e) {
            var _this$props = _this.props,
                onPressEnter = _this$props.onPressEnter,
                onKeyDown = _this$props.onKeyDown;

            if (e.keyCode === 13 && onPressEnter) {
                onPressEnter(e);
            }
            if (onKeyDown) {
                onKeyDown(e);
            }
        };
        _this.saveInput = function (node) {
            _this.input = node;
        };

        _this.handleComposition = function (e) {
            if (e.type === 'compositionend') {
                // composition is end
                _this.isOnComposition = false;
                if (isNeedTriggerAfterComposition()) {
                    _this.handleChange(e);
                }
            } else {
                // in composition
                _this.isOnComposition = true;
            }
        };

        _this.handleBlur = function (e) {
            var value = e.target.value;
            var _this$props2 = _this.props,
                onChange = _this$props2.onChange,
                trim = _this$props2.trim,
                trimAll = _this$props2.trimAll,
                onBlur = _this$props2.onBlur;

            var trimValue = value;
            if (trim && isString(value)) {
                trimValue = value.trim();
            }
            if (trimAll && isString(value)) {
                trimValue = value.replace(/\s/g, '');
            }
            if (trimValue !== value) {
                _this.input.value = trimValue;
                if (onChange && isFunction(onChange)) {
                    e.target.value = trimValue;
                    onChange(e);
                }
            }
            if (onBlur && isFunction(onBlur)) {
                onBlur(e);
            }
        };

        _this.handleChange = function (e) {
            var onChange = _this.props.onChange;

            if (!_this.isOnComposition) {
                // 在 onChange 时记录光标的位置
                if (_this.input) {
                    _this.inputSelection = {
                        start: _this.input.selectionStart,
                        end: _this.input.selectionEnd
                    };
                }
                var transformValue = _this.transformValue(e.target.value);
                if (transformValue !== e.target.value) {
                    e.target.value = _this.transformValue(e.target.value);
                    if (_this.inputSelection && (_this.inputSelection.start || _this.inputSelection.end)) {
                        e.target.setSelectionRange(_this.inputSelection.start, _this.inputSelection.end);
                        _this.inputSelection = null;
                    }
                }
            }
            if (onChange && isFunction(onChange)) {
                onChange(e);
            }
        };
        return _this;
    }



    _createClass(Input, [{
        key: 'componentDidMount',
        value: function componentDidMount() {
            this.setState({
                type: this.props.type
            });
        }
    }, {
        key: 'componentDidUpdate',
        value: function componentDidUpdate(prevProps) {
            var inputSelection = this.inputSelection;
            var value = prevProps.value;

            if (inputSelection && value) {
                // 在 didUpdate 时根据情况恢复光标的位置
                // 如果光标的位置小于值的长度，那么可以判定属于中间编辑的情况
                // 此时恢复光标的位置
                if (inputSelection.start && this.transformValue(value).length && inputSelection.start < this.transformValue(value).length) {
                    var input = this.input;
                    input.selectionStart = inputSelection.start;
                    input.selectionEnd = inputSelection.end;
                    this.inputSelection = null;
                }
            }
        }
    }, {
        key: 'focus',
        value: function focus() {
            this.input.focus();
        }
    }, {
        key: 'blur',
        value: function blur() {
            this.input.blur();
        }
    }, {
        key: 'getInputClassName',
        value: function getInputClassName() {
            var _classNames;

            var _props = this.props,
                prefixCls = _props.prefixCls,
                size = _props.size,
                disabled = _props.disabled,
                typeCase = _props.typeCase;

            return classNames(prefixCls, (_classNames = {}, _defineProperty(_classNames, prefixCls + '-sm', size === 'small'), _defineProperty(_classNames, prefixCls + '-lg', size === 'large'), _defineProperty(_classNames, prefixCls + '-disabled', disabled), _defineProperty(_classNames, prefixCls + '-upper', typeCase === 'upper'), _defineProperty(_classNames, prefixCls + '-lower', typeCase === 'lower'), _classNames));
        }
    }, {
        key: 'renderLabeledInput',
        value: function renderLabeledInput(children) {
            var _classNames3;

            var props = this.props;
            // Not wrap when there is not addons
            if (!props.addonBefore && !props.addonAfter) {
                return children;
            }
            var wrapperClassName = props.prefixCls + '-group';
            var addonClassName = wrapperClassName + '-addon';
            var addonBefore = props.addonBefore ? React.createElement(
                'span',
                { className: addonClassName },
                props.addonBefore
            ) : null;
            var addonAfter = props.addonAfter ? React.createElement(
                'span',
                { className: addonClassName },
                props.addonAfter
            ) : null;
            var className = classNames(props.prefixCls + '-wrapper', _defineProperty({}, wrapperClassName, addonBefore || addonAfter));
            var groupClassName = classNames(props.prefixCls + '-group-wrapper', (_classNames3 = {}, _defineProperty(_classNames3, props.prefixCls + '-group-wrapper-sm', props.size === 'small'), _defineProperty(_classNames3, props.prefixCls + '-group-wrapper-lg', props.size === 'large'), _classNames3));
            // Need another wrapper for changing display:table to display:inline-block
            // and put style prop in wrapper
            if (addonBefore || addonAfter) {
                return React.createElement(
                    'span',
                    { className: groupClassName, style: props.style },
                    React.createElement(
                        'span',
                        { className: className },
                        addonBefore,
                        React.cloneElement(children, { style: null }),
                        addonAfter
                    )
                );
            }
            return React.createElement(
                'span',
                { className: className },
                addonBefore,
                children,
                addonAfter
            );
        }
    }, {
        key: 'renderLabeledIcon',
        value: function renderLabeledIcon(children) {
            var _classNames4;


            var props = _extends({}, this.props);
            var showPassword = this.state.showPassword;

            var classString = classNames('anticon', {
                'anticon-eye': !showPassword,
                'anticon-eye-o': showPassword
            });
            var eyePro = {
                onMouseDown: this.handleShowPassword,
                onMouseLeave: this.handleHidePassword,
                onMouseUp: this.handleHidePassword
            };
            if (this.props.type === 'password') {
                props = _extends({}, props, { suffix: React.createElement('i', _extends({ className: classString, style: { cursor: 'pointer' }, key: 'showPasswordIcon' }, eyePro)) });
            }
            if (!('prefix' in props || 'suffix' in props)) {
                return children;
            }
            var prefix = props.prefix ? React.createElement(
                'span',
                { className: props.prefixCls + '-prefix' },
                props.prefix
            ) : null;
            var suffix = props.suffix ? React.createElement(
                'span',
                { className: props.prefixCls + '-suffix' },
                props.suffix
            ) : null;
            var affixWrapperCls = classNames(props.className, props.prefixCls + '-affix-wrapper', (_classNames4 = {}, _defineProperty(_classNames4, props.prefixCls + '-affix-wrapper-sm', props.size === 'small'), _defineProperty(_classNames4, props.prefixCls + '-affix-wrapper-lg', props.size === 'large'), _classNames4));
            return React.createElement(
                'span',
                { className: affixWrapperCls, style: props.style },
                prefix,
                React.cloneElement(children, { style: null, className: this.getInputClassName() }),
                suffix
            );
        }


    }, {
        key: 'transformValue',
        value: function transformValue(v) {
            var _props2 = this.props,
                typeCase = _props2.typeCase,
                _props2$dbc2sbc = _props2.dbc2sbc,
                dbc2sbc = _props2$dbc2sbc === undefined ? true : _props2$dbc2sbc,
                inputChinese = _props2.inputChinese;

            var value = v;
            if (typeCase === 'upper') {
                value = upperCaseString(v);
            } else if (typeCase === 'lower') {
                value = lowerCaseString(v);
            }
            if (dbc2sbc && isDbc(v)) {
                value = dbcToSbc(v);
            }
            if (!inputChinese && isString(value)) {
                value = value.replace(/[\u4e00-\u9fa5]/g, '');
            }
            return value;
        }
    }, {
        key: 'renderInput',
        value: function renderInput() {
            var _props3 = this.props,
                value = _props3.value,
                className = _props3.className;
            var type = this.state.type;
            // Fix https://fb.me/react-unknown-prop

            var otherProps = omit(this.props, ['prefixCls', 'onPressEnter', 'addonBefore', 'addonAfter', 'prefix', 'suffix', 'form', 'onChange', 'dbc2sbc', 'typeCase', 'trim', 'trimAll', 'inputChinese', 'type']);
            if ('value' in this.props) {
                otherProps.value = fixControlledValue(value);
                // Input elements must be either controlled or uncontrolled,
                // specify either the value prop, or the defaultValue prop, but not both.
                delete otherProps.defaultValue;
            }
            return this.renderLabeledIcon(React.createElement('input', _extends({}, otherProps, { type: type
                , className: classNames(this.getInputClassName(), className), onKeyDown: this.handleKeyDown, onBlur: this.handleBlur
                , onChange: this.handleChange
                , onCompositionStart: this.handleComposition
                , onCompositionUpdate: this.handleComposition
                , onCompositionEnd: this.handleComposition
                , ref: this.saveInput })));
        }
    }, {
        key: 'render',
        value: function render() {
            return this.renderLabeledInput(this.renderInput());
        }
    }]);

    return Input;
}(React.Component);

export default Input;

Input.defaultProps = {
    prefixCls: 'ant-input',
    type: 'text',
    disabled: false,
    dbc2sbc: true,
    trim: true,
    trimAll: false,
    inputChinese: true
};
Input.propTypes = {
    type: PropTypes.string,
    id: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
    size: PropTypes.oneOf(['small', 'default', 'large']),
    maxLength: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
    disabled: PropTypes.bool,
    dbc2sbc: PropTypes.bool,
    value: PropTypes.any,
    defaultValue: PropTypes.any,
    className: PropTypes.string,
    addonBefore: PropTypes.node,
    addonAfter: PropTypes.node,
    prefixCls: PropTypes.string,
    autosize: PropTypes.oneOfType([PropTypes.bool, PropTypes.object]),
    onPressEnter: PropTypes.func,
    onKeyDown: PropTypes.func,
    onKeyUp: PropTypes.func,
    onFocus: PropTypes.func,
    onBlur: PropTypes.func,
    prefix: PropTypes.node,
    suffix: PropTypes.node
};